package cn.lj.service.Impl;

import cn.lj.dao.BookDao;
import cn.lj.domain.Appointment;
import cn.lj.domain.Book;
import cn.lj.domain.Student;
import cn.lj.dto.AppointExecution;
import cn.lj.exception.AppointException;
import cn.lj.exception.NoNumberException;
import cn.lj.exception.RepeatAppointException;
import cn.lj.service.BookService;
import cn.lj.util.AppointStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lj
 * @Description:
 * @date 2020-12-04 14:15
 * @QQ 851477108
 */

@Service
public class BookServiceImpl implements BookService {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BookDao bookDao;

    @Override
    public List<Book> findAll() {
        return bookDao.findAll(0,1000);
    }

    @Override
    public Book findById(Long id) {
        return bookDao.findById(id);
    }

    @Override
    public List<Book> findListByName(String name) {
        return bookDao.findListByName(name);
    }

    @Override
    public List<Appointment> findAppointByStu(Long studentId) {
        return bookDao.findAppointByStu(studentId);
    }

    @Override
    public Student checkStudent(Long studentId, Long password) {
        return bookDao.checkStudent(studentId,password);
    }

    @Transactional
    @Override
    public AppointExecution appoint(Long bookId, Long studentId) {
        //在Dao的基础上组织逻辑，形成与web成交互用的方法
        //返回成功预约的类型
        try {
            int update = bookDao.reduceNumber(bookId);
            if (update<=0) {
                throw new NoNumberException("no number");
            }else {
                int i = bookDao.insertAppointment(bookId, studentId);
                if (i <= 0){
                    throw new RepeatAppointException("重复预约");
                }else {
                    return new AppointExecution(bookId,AppointStateEnum.SUCCESS);
                }
            }
        } catch (NoNumberException | RepeatAppointException e) {
            logger.error(e.getMessage(), e);
            // 所有编译期异常转换为运行期异常
            throw new AppointException("appoint inner error:" + e.getMessage());
        }
    }
}
